#!/usr/bin/python


import logging
import urllib
import re

from waveapi import events
from waveapi import robot

from waveapi.document import Range
from google.appengine.api import urlfetch

from BeautifulSoup import BeautifulStoneSoup

BASE_URL = "http://migre.me/api.xml?url="

urlfinders = [
    re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*[^]'\\.}>\\),\\\"]"),
    re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?"),
    re.compile("(~/|/|\\./)([-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]|\\\\)+"),
    re.compile("'\\<((mailto:)|)[-A-Za-z0-9\\.]+@[-A-Za-z0-9\\.]+"),
]

def GetNewURLFromMigreme(url):

    if not url.startswith("http://") and not url.startswith("https://") and not url.startswith("ftp://"):
         url = "http://"+url

    response = urlfetch.fetch(BASE_URL+url)
    xml = response.content
    soup = BeautifulStoneSoup(xml)

    return soup.item.migre.contents[0]

def OnBlipSubmitted(properties, context):
  
    blip = context.GetBlipById(properties['blipId']).GetDocument()
    blip_txt = blip.GetText()
    
    to_subs = ConvertURL(blip_txt)

    for r, new_url in to_subs:
        blip.SetTextInRange(r, str(new_url))
        

def MatchURL(url):
    for rex in urlfinders:
        if rex.match(url):
            return True
    return False       

def ConvertURL(text):

    text_words = text.split()
    urls = []
    offset = 0

    for word in text_words:
        if MatchURL(word):
            if not word.startswith("http://migre.me/") and (len(word) > 20):
                
                new_url = GetNewURLFromMigreme(word)
                start = text.find(word)+offset
                end = start + len(word)

                range = Range(start, end)
                new_data = (range, new_url)
                urls.append(new_data)

                offset = len(new_url) - len(word)
    return urls

if __name__ == '__main__':
    hobbity = robot.Robot('Hobbity', 
        image_url='http://hobbiturl.appspot.com/assets/icon.jpg',
        version='3',
        profile_url='http://hobbiturl.appspot.com/')

    hobbity.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)

    hobbity.Run()
